package cn.softgame.cms.open.authentication.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import cn.softgame.cms.open.authentication.domain.IpranUserDetails;
import cn.softgame.cms.open.authentication.domain.SysRight;
import cn.softgame.cms.open.authentication.domain.SysUser;

@Component
public class IpranUserDetailsService implements UserDetailsService {//必须实现UserDetailsService接口定义
	
	private static final Logger logger = Logger.getLogger(IpranUserDetailsService.class);
	
	@Autowired
	private SysUserService sysUserService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		if (username == null || "".equals(username.trim())) {
			throw new UsernameNotFoundException("Username was empty");
		}
		SysUser sysUser = sysUserService.getSysUser(username);
		if(logger.isDebugEnabled()){
			logger.debug("=========User rights：" + sysUser.getSysRights());
		}
		if (sysUser == null) {
			throw new UsernameNotFoundException("Username not found");
		}

		List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
		
		if(sysUser.getSysRights()!=null){
			for (SysRight sysRight : sysUser.getSysRights()) {
				grantedAuthorities.add(new SimpleGrantedAuthority(sysRight.getRightCode()));
			}
		}
		return new IpranUserDetails(sysUser, grantedAuthorities);
	}
}